package com.qfhd.soft.cjzcore.TaskCenter.CSJ;

import android.app.Activity;
import android.content.Context;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdManager;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.qfhd.soft.cjzcore.Core.CJLogger;
import com.qfhd.soft.cjzcore.Core.CJScreenUtil;
import com.qfhd.soft.cjzcore.Listener.CJAdListener;
import com.qfhd.soft.cjzcore.TaskCenter.CJAdCenter;
import com.qfhd.soft.cjzcore.TaskCenter.TTAdManagerHolder;
import com.qfhd.soft.cjzcore.User.CJZUser;

public class CJCSJ_RewardVideo {

    private TTRewardVideoAd mttRewardVideoAd = null;
    private boolean mHasShowDownloadActive = false;

    private static CJCSJ_RewardVideo rewardVideo;
    public static CJCSJ_RewardVideo getInstance() {
        if (rewardVideo == null) {
            synchronized (CJCSJ_RewardVideo.class) {
                rewardVideo = new CJCSJ_RewardVideo();
            }
        }
        return rewardVideo;
    }

    public void show(Activity activity , Context context, CJAdListener statusListener){
        //step1:初始化sdk
        TTAdManager ttAdManager = TTAdManagerHolder.get();
        //step2:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdManagerHolder.get().requestPermissionIfNecessary(context);
        //step3:创建TTAdNative对象,用于调用广告请求接口
        TTAdNative mTTAdNative = ttAdManager.createAdNative(context);

        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = new AdSlot.Builder()
                .setCodeId(CJCSJsdk.RewardVideo)
                .setSupportDeepLink(true)
                .setImageAcceptedSize((int)CJScreenUtil.getScreenWidthDp(context), (int)CJScreenUtil.getHeight(activity))
                .setRewardName("金币") //奖励的名称
                .setRewardAmount(3)  //奖励的数量
                .setUserID(CJZUser.getInstance().getUserInfo().account)//用户id,必传参数
                .setMediaExtra("media_extra") //附加参数，可选
                .setOrientation(TTAdConstant.VERTICAL) //必填参数，期望视频的播放方向：TTAdConstant.HORIZONTAL 或 TTAdConstant.VERTICAL
                .build();
        //step5:请求广告
        mTTAdNative.loadRewardVideoAd(adSlot, new TTAdNative.RewardVideoAdListener() {
            @Override
            public void onError(int code, String message) {
//                TToast.show(RewardVideoActivity.this, message);
                CJLogger.v("error:" + message);
            }

            //视频广告加载后，视频资源缓存到本地的回调，在此回调后，播放本地视频，流畅不阻塞。
            @Override
            public void onRewardVideoCached() {
//                TToast.show(RewardVideoActivity.this, "rewardVideoAd video cached");
                mttRewardVideoAd.showRewardVideoAd(activity);
            }

            //视频广告的素材加载完毕，比如视频url等，在此回调后，可以播放在线视频，网络不好可能出现加载缓冲，影响体验。
            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd ad) {
//                TToast.show(RewardVideoActivity.this, "rewardVideoAd loaded");
                mttRewardVideoAd = ad;
                mttRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {

                    @Override
                    public void onAdShow() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd show");
                    }

                    @Override
                    public void onAdVideoBarClick() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd bar click");
                        if(statusListener != null){
                            statusListener.onStatus(CJAdCenter.AD_Status_Click);
                        }
                    }

                    @Override
                    public void onAdClose() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd close");
                        CJLogger.v("video close");
                        if(statusListener != null){
                            statusListener.onStatus(CJAdCenter.AD_Status_Close);
                        }
                    }

                    //视频播放完成回调
                    @Override
                    public void onVideoComplete() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd complete");

                    }

                    @Override
                    public void onVideoError() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd error");
                    }

                    //视频播放完成后，奖励验证回调，rewardVerify：是否有效，rewardAmount：奖励梳理，rewardName：奖励名称
                    @Override
                    public void onRewardVerify(boolean rewardVerify, int rewardAmount, String rewardName) {
//                        TToast.show(RewardVideoActivity.this, "verify:" + rewardVerify + " amount:" + rewardAmount +
//                                " name:" + rewardName);
                        if(statusListener != null){
                            statusListener.onStatus(CJAdCenter.AD_Status_Reward);
                        }
//                        new Thread(() -> {
//                            boolean ret = CJUser.getInstence().uploadAction(CJTaskCenter.Task_Type_TMSDK_Video_Watch, CJTime.getCurrentTimeMillis() + "_CSJ_" + CJUser.getInstence().getAccount());
//                            if (ret) {
//                                CJUser.getInstence().addCoin(CJConstants.TASK_VIDEO_WATCH_COIN);
//                                CJUser.getInstence().setTask_video(1);
//
//                                activity.runOnUiThread(() -> {
//                                    showData();
//                                    coinDialog = new CJCoinDialog(mContext, CJConstants.TASK_VIDEO_WATCH_COIN);
//                                    coinDialog.setOnclickListeter(v -> coinDialog.dismiss());
//                                    coinDialog.show();
//                                });
//
//                            } else {
//                                activity.runOnUiThread(() -> {
//                                    CJCore.Toast(context, "网络错误", false);
//                                });
//                            }
//                        }).start();
                    }

                    @Override
                    public void onSkippedVideo() {
//                        TToast.show(RewardVideoActivity.this, "rewardVideoAd has onSkippedVideo");
                    }
                });
                mttRewardVideoAd.setDownloadListener(new TTAppDownloadListener() {
                    @Override
                    public void onIdle() {
                        mHasShowDownloadActive = false;
                    }

                    @Override
                    public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                        if (!mHasShowDownloadActive) {
                            mHasShowDownloadActive = true;
//                            TToast.show(RewardVideoActivity.this, "下载中，点击下载区域暂停", Toast.LENGTH_LONG);
                        }
                    }

                    @Override
                    public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
//                        TToast.show(RewardVideoActivity.this, "下载暂停，点击下载区域继续", Toast.LENGTH_LONG);
                    }

                    @Override
                    public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
//                        TToast.show(RewardVideoActivity.this, "下载失败，点击下载区域重新下载", Toast.LENGTH_LONG);
                    }

                    @Override
                    public void onDownloadFinished(long totalBytes, String fileName, String appName) {
//                        TToast.show(RewardVideoActivity.this, "下载完成，点击下载区域重新下载", Toast.LENGTH_LONG);
                        if(statusListener != null){
                            statusListener.onStatus(CJAdCenter.AD_Status_Download);
                        }
                    }

                    @Override
                    public void onInstalled(String fileName, String appName) {
//                        TToast.show(RewardVideoActivity.this, "安装完成，点击下载区域打开", Toast.LENGTH_LONG);
                        if(statusListener != null){
                            statusListener.onStatus(CJAdCenter.AD_Status_Install);
                        }
                    }
                });
            }
        });
    }
}
